<script setup lang="ts">
import { ref, watch } from 'vue';
import { quasarFormStyle } from '@/setting.ts';
import type { Role } from '@/api/acl/role-type.ts';
import { reqSaveOrUpdateRole } from '@/api/acl/role.ts';
import { useQuasar, QForm } from 'quasar';
import { useCompRef } from '@/utils/useCompRef';

const { notify } = useQuasar();
const $emit = defineEmits<{
  refreshData: [flag?: string];
}>();
type FormType = 'SAVE' | 'UPDATE';
enum TITLE {
  SAVE = '添加职位',
  UPDATE = '更新职位'
}
const dialogType = ref<FormType>();
function showFormDialog(type: FormType, role?: Role) {
  if (role) {
    roleInfo.value = { ...role };
  } else {
    roleInfo.value = {
      roleName: ''
    };
  }
  dialogType.value = type;
  isShowDialog.value = true;
}
defineExpose({ showFormDialog });
// 显示dialog
const isShowDialog = ref<boolean>(false);
// 用户基本信息
const roleInfo = ref<Role>({
  roleName: ''
});

const qFormCom = useCompRef(QForm);
// 提交数据
async function onSubmit() {
  const error = await qFormCom.value?.validate();
  if (!error) return;
  try {
    const result = await reqSaveOrUpdateRole(roleInfo.value);
    if (result.code === 200) {
      notify({
        type: 'positive',
        message: `${TITLE[dialogType.value!]}成功`,
        position: 'top'
      });
      $emit('refreshData', 'ok');
      isShowDialog.value = false;
    } else {
      throw new Error(`${TITLE[dialogType.value!]}失败`);
    }
  } catch (error: any) {
    notify({
      type: 'negative',
      message: error.message,
      position: 'top'
    });
  }
}
</script>

<template>
  <q-dialog v-model="isShowDialog">
    <q-card>
      <q-card-section>
        <span class="text-h6">{{ TITLE[dialogType!] }}</span>
      </q-card-section>
      <q-card-section>
        <q-form
          class="q-pl-lg q-gutter-xs"
          ref="qFormCom"
          style="min-width: 300px"
        >
          <q-input
            v-bind="quasarFormStyle"
            dense
            label="职位名称"
            v-model="roleInfo.roleName"
            :rules="[val => !!val || '职位名称不能为空']"
          />
        </q-form>
      </q-card-section>
      <q-card-actions align="right">
        <q-btn
          label="取消"
          color="primary"
          flat
          @click="isShowDialog = false"
        />
        <q-btn label="提交" color="primary" @click="onSubmit" />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<style scoped lang="scss">
.checkbox_all {
  position: absolute;
  left: 80px;
  top: 0;
}
</style>
